import Vue from 'vue'
import { Loading } from 'element-ui'

const toggleLoading = (el, binding, target) => {
  if (binding.value) {
    Vue.nextTick(() => {
      const loadingInstance = Loading.service({
        target,
        fullscreen: false
      })
      if (!el._bcLoadingInstance) el._bcLoadingInstance = {}
      el._bcLoadingInstance.loadingInstance = loadingInstance
      el._bcLoadingInstance.visible = true
    })
  } else {
    if (!el._bcLoadingInstance) el._bcLoadingInstance = {}
    if (el._bcLoadingInstance.visible === true) {
      el._bcLoadingInstance.loadingInstance && el._bcLoadingInstance.loadingInstance.close()
      el._bcLoadingInstance.visible = false
    }
  }
}

Vue.directive('table-loading', {
  bind(el, binding, vnode) {
    if (binding.value) {
      const target = el.querySelector('.el-table__body-wrapper')
      target && toggleLoading(el, binding, target)
    }
  },
  update(el, binding, vnode, oldVnode) {
    if (binding.oldValue !== binding.value) {
      const target = el.querySelector('.el-table__body-wrapper')
      target && toggleLoading(el, binding, target)
    }
  },
  unbind(el, binding, vnode) {
    if (el._bcLoadingInstance) {
      if (el._bcLoadingInstance.visible === true) {
        el._bcLoadingInstance.loadingInstance && el._bcLoadingInstance.loadingInstance.close()
      }
      el._bcLoadingInstance = null
      delete el._bcLoadingInstance
    }
  }
})
